package com.example.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bean.User;
import com.example.service.UserService;
import com.example.until.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;


/**
 * @title: UserController
 * @Author wjf
 * @Date: 2022/9/19 19:13
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/page")
    public Result<IPage<User>> getAllUser(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam String username,
            @RequestParam String email,
            @RequestParam String address) {
        IPage<User> page = new Page<>(current, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(username), "username", username)
                .like(StringUtils.isNotBlank(email), "email", email)
                .like(StringUtils.isNotBlank(address), "address", address)
                .orderByDesc("id");

        IPage<User> page1 = userService.page(page, queryWrapper);

        return Result.ok(page1);

        //        User currentUser = TokenUtils.getCurrentUser();
//        System.out.println("当前用户信息:============="+currentUser);

    }

    /**
     * 获取教师信息
     * @param current
     * @param pageSize
     * @param username
     * @param email
     * @param address
     * @return
     */
    @GetMapping("/teacher/page")
    public Result<IPage<User>> getAllTeacher(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam String username,
            @RequestParam String email,
            @RequestParam String address) {
        IPage<User> page = new Page<>(current, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(username), "username", username)
                .like(StringUtils.isNotBlank(email), "email", email)
                .like(StringUtils.isNotBlank(address), "address", address)
                .eq("role","老师")
                .orderByDesc("id");

        IPage<User> page1 = userService.page(page, queryWrapper);

        return Result.ok(page1);
    }

    @GetMapping({"/byName/{username}"})
    @CrossOrigin(allowCredentials = "true")
    public Result getUserByName(@PathVariable String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(username),"username",username);
        User one = userService.getOne(queryWrapper);
        return Result.ok(one);
    }

    @GetMapping("/{id}")
    @CrossOrigin
    public Result<User> getUserById(@PathVariable("id") Integer id){
        User user = userService.getById(id);
        return Result.ok(user);
    }

    @PostMapping("/save")
    @CrossOrigin
    public Result<Boolean> saveUser(@RequestBody User user) {
        boolean save = userService.save(user);
        return Result.ok(save);
    }

    @PutMapping("/update")
    @CrossOrigin(allowCredentials = "true")
    public Result<Boolean> putUser(@RequestBody User user) {
        boolean b = userService.updateById(user);
        return Result.ok(b);
    }

    @DeleteMapping("/delete/{id}")
    @CrossOrigin
    public Result<Boolean> deleteUser(@PathVariable Integer id) {
        boolean b = userService.removeById(id);
        return Result.ok(b);
    }

    @DeleteMapping("/delete/batch/{ids}")
    public Result<Boolean> deleteMoreUser(@PathVariable List<Integer> ids){
        boolean b = userService.removeByIds(ids);
        return Result.ok(b);
    }

    /**
     * 找出老师
     */
    @GetMapping("/teacher")
    public Result getTeachers(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role","老师");
        List<User> teachers = userService.list(queryWrapper);
        return Result.ok(teachers);
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<User> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatarUrl", "头像");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
//        List<List<Object>> list = reader.read(1);
//        List<User> users = CollUtil.newArrayList();
//        for (List<Object> row : list) {
//            User user = new User();
//            user.setUsername(row.get(0).toString());
//            user.setPassword(row.get(1).toString());
//            user.setNickname(row.get(2).toString());
//            user.setEmail(row.get(3).toString());
//            user.setPhone(row.get(4).toString());
//            user.setAddress(row.get(5).toString());
//            user.setAvatarUrl(row.get(6).toString());
//            users.add(user);
//        }
        userService.saveBatch(list);
        return true;
    }
}